package com.example.partybuilding.controller;

import com.example.partybuilding.service.QuestionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.ContentDisposition;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;

@Controller
public class QuestionController {

    @Autowired
    private QuestionService questionService;

    @GetMapping("/")
    public String index(@RequestParam(defaultValue = "1") int page, Model model) {
        int pageSize = 10;
        List<Map.Entry<Integer, String>> paginatedQuestions = questionService.getPaginatedQuestions(page, pageSize);
        int totalPages = questionService.getTotalPages(pageSize);

        model.addAttribute("questions", paginatedQuestions);
        model.addAttribute("currentPage", page);
        model.addAttribute("totalPages", totalPages);

        return "index";
    }

    @GetMapping("/answer")
    public String getAnswer(@RequestParam Integer id, Model model) {
        String answer = questionService.getAnswerById(id);
        if (answer != null) {
            model.addAttribute("question", questionService.getQuestionById(id));
            model.addAttribute("answer", answer);
        } else {
            model.addAttribute("error", "问题编号无效");
        }
        return "answer";
    }

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile() throws IOException {
        Path path = Paths.get("src/main/resources/files/问答系统答案.zip");
        Resource resource = new FileSystemResource(path.toFile());

        String filename = "问答系统答案.zip";
        ContentDisposition contentDisposition = ContentDisposition.attachment()
                .filename(filename, java.nio.charset.StandardCharsets.UTF_8)
                .build();

        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition.toString())
                .body(resource);
    }
}